package com.gsq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gsq.common.pojo.Admin;
import com.gsq.common.pojo.User;
import com.gsq.common.vo.PageResult;
import com.gsq.mapper.UserMapper;
import com.gsq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageResult getUserList(PageResult pageResult) {
        IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "username",pageResult.getQuery());
        iPage = userMapper.selectPage(iPage, queryWrapper);
        long total = iPage.getTotal();
        List<Admin> rows = iPage.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }
    /*  添加用户    */
    @Override
    public void addUser(User user) {
        //1. 获取注册的密码
        String password = user.getPassword();
        //2. 密码进行md5加密
        String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //3. 获取随机盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
        //4. 截取md5部分
        String partMd5Str = md5Pwd.substring(5,16);
        //5. 拼接新密码
        String newPassword = DigestUtils.md5DigestAsHex((md5Pwd + partMd5Str + salt).getBytes());
        if (user.getSalt()==null)
            user.setSalt(newPassword);
        user.setUserStatus(true).setPassword(md5Pwd);
        userMapper.insert(user);
    }
    /* 修改状态 */
    @Override
    public void updatedValid(User user) {
        userMapper.updateById(user);
    }
    /* 修改用户信息 */
    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public User findUser(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }
}
